<?php
/**
 * Created by PhpStorm.
 * User: PanChaoZhi
 * Date: 2017/1/21
 * Time: 19:37
 */
/*
 * 加入购物车操作
 * 1.接受传递过来的数据post参数
 * 2.准备要添加的购物车数据
 * 3.完成购物车数据的添加操作
 * 4.返回最终添加的结果
 */
session_start();
require_once 'lib/mysqli_func.php';
//1.接收传递过来的参数
//strip_tags()从字符串中除去HTML和PHP标记，第一个参数可以指定不被去除的标记
$productid = strip_tags($_POST['productid']);
$num = strip_tags($_POST['num']);

//2.准备要添加的购物车数据
try {
    if (!isset($_SESSION['login_id'])) {
        $response = array(
            'errno' => -1,
            'errmsg' => 'addcart_fali',
            'data' => false,
        );
    } else {
        $pdo = new PDO('mysql:host=localhost;dbname=shopimooc', 'root', 'localhost', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
        $pdo->query("set names utf8");
        $sql = "select iPrice from imooc_pro where id=?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute(array($productid));
        $data = $stmt->fetch(PDO::FETCH_ASSOC);
        //var_dump($data);
        $price = $data['iPrice'];
        $created = time();
        $userid = $_SESSION['login_id'];

        //3.完成购物车数据的添加操作(优化：判断当前用户是否已经添加过该商品)
        $sql = "SELECT * FROM imooc_cart WHERE pro_id=? AND user_id=?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute(array($productid, $userid));
        $data = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($data) {
            $sql = "UPDATE imooc_cart set num=num+? WHERE user_id=? AND pro_id=?";
            $param = array($num, $userid, $productid);
        } else {
            $sql = "INSERT INTO imooc_cart(pro_id, user_id, num, price, created) VALUES(?,?,?,?,?)";
            $param = array($productid, $userid, $num, $price, $created);
        }

        $stmt = $pdo->prepare($sql);
        $stmt->execute($param);
        $rows = $stmt->rowCount();

        //4.返回最终添加的结果，是一个 json 格式的数据
        if ($rows) {
            $response = array(
                'errno' => 0,
                'errmsg' => 'success',
                'data' => true,
            );
        } else {
            $response = array(
                'errno' => 1,
                'errmsg' => 'fail',
                'data' => false,
            );
        }
    }
    echo json_encode($response);
} catch (PDOException $e) {
    echo $e->getMessage();
}

